package com.sig.service;

import com.sig.bean.Permission;
import com.sig.bean.Role;
import com.sig.bean.User;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.entity.Record;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.List;

/**
 * @author sig
 * @since 2016-6-23 11:03:53
 */
@IocBean(name = "authorityService")
public class AuthorityServiceImpl implements AuthorityService {
    @Inject()
    private Dao dao;

    @Override
    public void initFormPackage(String pkg) {

    }

    @Override
    public void checkBasicRoles(User admin) {
        // 检查一下admin的权限
        Role adminRole = dao.fetch(Role.class, "admin");

        if (adminRole == null) {
            adminRole = addRole("admin");
        }

        // admin账号必须存在与admin组
        if (0 == dao.count("user_role",
                Cnd.where("u_id", "=", admin.getId()).and("role_id", "=", adminRole.getId()))) {
            dao.insert("user_role",
                    Chain.make("u_id", admin.getId()).add("role_id", adminRole.getId()));
        }
        // admin组必须有authority:* 也就是权限管理相关的权限
        List<Record> res = dao.query("role_permission", Cnd.where("role_id", "=", adminRole.getId()));

        for (Permission permission : dao.query(Permission.class,
                Cnd.where("name", "like", "authority:%").or("name", "like", "user:%"), null)) {

            for (Record re : res) {

                if (re.getInt("permission_id") == permission.getId()) {
                    break;
                }
            }
            dao.insert("role_permission",
                    Chain.make("role_id", adminRole.getId()).add("permission_id", permission.getId()));
        }
    }

    @Override
    public void addPermission(String permission) {

    }

    @Override
    public Role addRole(String role) {
        return null;
    }
}
